package com.shujia.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.Arrays;

public class Code03GetData {
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZooKeeper zooKeeper = new ZooKeeper("master:2181",
                15 * 1000,
                new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        System.out.println("process函数执行了...");
                    }
                }
        );

        String path = "/api";
        Stat exists = zooKeeper.exists(path, false);

//        System.out.println(exists);
        if (exists != null) {
            // 获取数据
            byte[] data = zooKeeper.getData(path, new Watcher() {
                        @Override
                        public void process(WatchedEvent event) {
                            System.out.println("变化的类型："+event.getWrapper().getType());
                            System.out.println("变化的路径："+event.getWrapper().getPath());
                            System.out.println("获取到数据变化...");
                        }
                    },
                    exists
            );

            Thread.sleep(10 * 1000);

//            String s = Arrays.toString(data);
            String dataStr = new String(data);

            System.out.println(dataStr);

        } else {
            System.out.println("当前给定节点不存在...");
        }


        zooKeeper.close();


    }
}
